import Toolbar from './utils/toolbar.js'
import { BASE_OPTIONS } from './plugins/options.js'

export default class XEditor {
    constructor(dom, options) {
        this._initEditor(dom)
        this._initOptions(options)
        this._initToolbar()
        this._initEvent()
    }

    _initEditor(dom) {
        this._editor = dom instanceof HTMLElement ? dom : document.querySelector(dom)
        this._editor.classList.add('x-editor')
        this._editor.innerHTML = '<div class="x-editor-content" contenteditable="true"/>'
        this._input = this._editor.querySelector('.x-editor-content')
    }

    _initToolbar() {
        this._toolbar = new Toolbar(this)
        const toolbar = document.createElement('ul')
        toolbar.classList.add('x-editor-toolbar')
        this._editor.prepend(toolbar)
        for (const plugin of this._toolbar._plugins) {
            toolbar.appendChild(plugin.getDom())
        }
    }

    _initOptions(options) {
        this._options = Object.assign(BASE_OPTIONS, options)
        const cssStyle = getComputedStyle(this._editor)
        for (let key in this._options) {
            if (key in cssStyle) {
                this._input.style[key] = this._options[key]
            } else {
                switch (key) {
                    case 'placeholder':
                        this._input.setAttribute(key, this._options[key])
                }
            }
        }
    }

    _initToggleEvent() {
        window.addEventListener('click', ({ target }) => {
            if (target.classList.contains('plugin-popover') || target.classList.contains('plugin-trigger')) {
                return
            }
            const activePopover = this._editor.querySelector('.plugin-popover-active')

            // const activePlugin = this._editor.querySelector('li.plugin-active')

            if (activePopover) {
                !activePopover.contains(target) && activePopover.classList.toggle('plugin-popover-active')
            }
            // if (activePlugin) {
            //     !activePlugin.contains(target) && activePlugin.classList.toggle('plugin-active')
            // }
        }, true)
    }

    _initEvent() {
        this._initToggleEvent()
    }

    setContent = function(html) {
        this._input.innerHTML = html
    }

    getHTML = function() {
        return this._input.innerHTML
    }

    getContext = function() {
        return this._input.textContent
    }
}